package com.angcyo.selenium.auto.controller

import com.angcyo.javafx.base.BaseController
import com.angcyo.javafx.base.ex.find
import com.angcyo.javafx.ui.DslStage
import com.angcyo.javafx.ui.toImage
import com.angcyo.javafx.ui.visible
import javafx.scene.Parent
import javafx.scene.control.Button
import javafx.scene.control.Label
import javafx.scene.control.TextField
import javafx.scene.image.ImageView
import javafx.stage.Stage
import java.io.File
import java.net.URL
import java.util.*

/**
 * Email:angcyo@126.com
 * @author angcyo
 * @date 2021/01/15
 */
class PutTextController : BaseController() {
    override fun initialize(location: URL?, resources: ResourceBundle?) {
        super.initialize(location, resources)
    }
}

/**输入舞台*/
fun dslPutStage(
    title: String,
    tipLabel: String,
    promptText: String,
    tipTextLabel: String? = null,
    init: ((Stage, Parent) -> Unit)? = null
): String? {
    var result: String? = null
    DslStage().apply {
        rootFxml = "put_text.fxml"
        initStage = { stage, parent ->
            stage.isResizable = false
            stage.title = title

            parent.find<Label>("#tipLabel")?.text = tipLabel
            parent.find<Label>("#tipTextLabel")?.apply {
                text = tipTextLabel
                visible(tipTextLabel != null)
            }

            val inputNode: TextField? = parent.find("#inputNode")
            inputNode?.promptText = promptText

            parent.find<Button>("#okButton")?.setOnAction {
                result = inputNode?.text
                stage.close()
            }
            parent.find<Button>("#cancelButton")?.setOnAction {
                stage.close()
            }

            init?.invoke(stage, parent)
        }
        showAndWait()
    }
    return result
}

fun dslPutCode(imageBase64OrImageFile: String?): String? {
    return dslPutStage("请输入验证码", "请输入验证码:", "图中的验证码") { stage, parent ->
        val imageView: ImageView? = parent.find("#imageView")
        if (!imageBase64OrImageFile.isNullOrEmpty()) {
            val file = File(imageBase64OrImageFile)
            imageView?.image = if (file.exists()) {
                file.toImage()
            } else {
                imageBase64OrImageFile.toByteArray().toImage()
                //Base64.getMimeDecoder().decode(imageBase64OrImageFile).toImage()
            }
        }
    }
}

fun dslPutText(init: ((Stage, Parent) -> Unit)? = null): String? {
    return dslPutStage("输入内容", "请输入内容:", "需要输入的内容", null, init)
}